<template>
    <div class="sm4-container">
        <div class="control-panel">
            <div class="options-panel">
                <div class="key-section">
                    <div class="key-input">
                        <span>密钥:</span>
                        <n-input
                            v-model:value="key"
                            placeholder="请输入16位密钥"
                            :maxlength="16"
                            class="key-field"
                        />
                    </div>
                    <div class="iv-input" v-if="cipherMode === 'cbc'">
                        <span>IV:</span>
                        <n-input
                            v-model:value="iv"
                            placeholder="请输入16位初始向量"
                            :maxlength="16"
                            class="iv-field"
                        />
                    </div>
                </div>
                <div class="mode-options">
                    <n-space align="center">
                        <n-radio-group v-model:value="mode">
                            <n-radio-button key="encrypt" value="encrypt">加密</n-radio-button>
                            <n-radio-button key="decrypt" value="decrypt">解密</n-radio-button>
                        </n-radio-group>
                        <n-select
                            v-model:value="cipherMode"
                            :options="cipherModeOptions"
                            class="mode-select"
                        />
                    </n-space>
                </div>
            </div>
            <n-button @click="clearAll">清空</n-button>
        </div>

        <div class="content-panel">
            <!-- 输入区域 -->
            <div class="input-section">
                <div class="section-header">
                    <span>输入</span>
                    <div class="actions">
                        <n-button quaternary size="small" @click="clearInput">
                            清空
                        </n-button>
                    </div>
                </div>
                <n-input
                    v-model:value="inputText"
                    type="textarea"
                    :autosize="{ minRows: 5, maxRows: 10 }"
                    :placeholder="mode === 'encrypt' ? '请输入要加密的文本' : '请输入要解密的文本'"
                />
            </div>

            <!-- 转换按钮 -->
            <div class="action-panel">
                <n-button 
                    type="primary" 
                    @click="processText" 
                    :disabled="!canProcess"
                >
                    {{ mode === 'encrypt' ? '加密' : '解密' }}
                </n-button>
            </div>

            <!-- 输出区域 -->
            <div class="output-section">
                <div class="section-header">
                    <span>输出</span>
                    <div class="actions">
                        <n-button quaternary size="small" @click="copyOutput" :disabled="!outputText">
                            复制
                        </n-button>
                        <n-button quaternary size="small" @click="clearOutput" :disabled="!outputText">
                            清空
                        </n-button>
                    </div>
                </div>
                <n-input
                    v-model:value="outputText"
                    type="textarea"
                    :autosize="{ minRows: 5, maxRows: 10 }"
                    readonly
                    placeholder="处理结果将显示在这里"
                />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { sm4 } from 'sm-crypto'
import view from '@renderer/util/ui/ViewUtil'

// 加解密选项
const mode = ref<'encrypt' | 'decrypt'>('encrypt')
const cipherMode = ref<'ecb' | 'cbc'>('ecb')
const key = ref('')
const iv = ref('')
const inputText = ref('')
const outputText = ref('')

// 加密模式选项
const cipherModeOptions = [
    { label: 'ECB', value: 'ecb' },
    { label: 'CBC', value: 'cbc' }
]

// 是否可以处理
const canProcess = computed(() => {
    const hasValidKey = key.value.length === 16
    const hasValidIv = cipherMode.value === 'cbc' ? iv.value.length === 16 : true
    return hasValidKey && hasValidIv && inputText.value.trim().length > 0
})

// 将字符串转换为16进制字符串
const stringToHex = (str: string): string => {
    let hex = ''
    for (let i = 0; i < str.length; i++) {
        hex += str.charCodeAt(i).toString(16).padStart(2, '0')
    }
    return hex
}

// 处理文本
const processText = () => {
    if (!canProcess.value) {
        if (key.value.length !== 16) {
            view.alertErrorMessage('请输入16位密钥')
        } else if (cipherMode.value === 'cbc' && iv.value.length !== 16) {
            view.alertErrorMessage('请输入16位初始向量')
        } else {
            view.alertErrorMessage('请输入要处理的文本')
        }
        return
    }

    try {
        // 将密钥和IV转换为16进制字符串
        const hexKey = stringToHex(key.value)
        const hexIv = cipherMode.value === 'cbc' ? stringToHex(iv.value) : undefined
        
        if (mode.value === 'encrypt') {
            // 加密
            outputText.value = sm4.encrypt(
                inputText.value, 
                hexKey,
                { 
                    mode: cipherMode.value,
                    iv: hexIv 
                }
            )
        } else {
            // 解密
            outputText.value = sm4.decrypt(
                inputText.value, 
                hexKey,
                { 
                    mode: cipherMode.value,
                    iv: hexIv 
                }
            )
        }
    } catch (error) {
        view.alertErrorMessage(mode.value === 'encrypt' ? '加密失败' : '解密失败')
        console.error('SM4处理失败:', error)
    }
}

// 复制输出
const copyOutput = async () => {
    try {
        await navigator.clipboard.writeText(outputText.value)
        view.alertSuccessMessage('复制成功')
    } catch (error) {
        view.alertErrorMessage('复制失败')
    }
}

// 清空输入
const clearInput = () => {
    inputText.value = ''
    outputText.value = ''
}

// 清空输出
const clearOutput = () => {
    outputText.value = ''
}

// 清空所有
const clearAll = () => {
    key.value = ''
    iv.value = ''
    clearInput()
}

// 监听加密/解密模式变化
watch(mode, () => {
    clearInput()
})

// 监听加密算法模式变化
watch(cipherMode, () => {
    clearInput()
})
</script>

<style scoped>
.sm4-container {
    height: 100%;
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.control-panel {
    display: flex;
    gap: 16px;
    padding: 16px;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    align-items: flex-start;
}

.options-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.key-section {
    display: flex;
    gap: 16px;
    align-items: center;
}

.key-input,
.iv-input {
    display: flex;
    align-items: center;
    gap: 8px;
}

.key-field {
    width: 240px;
}

.iv-field {
    width: 240px;
}

.content-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 16px;
    min-height: 0;
}

.input-section,
.output-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;
    min-height: 0;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.actions {
    display: flex;
    gap: 8px;
}

.action-panel {
    display: flex;
    justify-content: center;
    padding: 16px 0;
}

.mode-options {
    display: flex;
    align-items: center;
    gap: 8px;
}

.mode-select {
    width: 120px;
}
</style>